package com.alex.jvm.reference;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 设置堆最大大小: -Xmx:20m
 * 打印GC详情: -XX:+PrintGCDetails -verbose:gc
 * jvm参数设置: -Xmx20m -XX:+PrintGCDetails -verbose:gc
 * 使用弱引用
 */
public class WeakReferenceDemo1 {

    private static final int _4M = 1024 * 1024 * 4; // 4M

    public static void main(String[] args) {
         weakReference();
         // YGC: 只会回收一个
        // FGC: 会回收全部的数据.
    }

    private static void weakReference() {
        List<WeakReference<byte[]>> data = new ArrayList<>();
        for (int i = 0; i < 15; i++) {
            WeakReference<byte[]> weakReference = new WeakReference<>(new byte[_4M]);
            data.add(weakReference);

            for (WeakReference item : data) {
                System.out.print(item.get() + ", ");
            }

            System.out.println();
        }
    }

}


